#include "fileprogress.h"
#include<QFile>
#include<QFileInfo>
#include<QThread>
#include"clientSock.h"
#include<iostream>
#include<QDebug>
#include"recivedata.h"
#include<fstream>
#include"loadform.h"
#include<QDir>
#include<QFileInfo>
#include<QIODevice>
//#include<functional>


#define BufferSize 1024*20

FileProgress::FileProgress(QObject *parent) : QObject(parent)
{
    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::DownFile,this,&FileProgress::downFile);
}

std::mutex &FileProgress::fileMutex(std::string &fileIdenter)
{
    std::lock_guard<std::mutex> lk(fileWriteMutex);
    return fileWriteMutexMap[fileIdenter]; // 如果不存在，会自动创建
}

void FileProgress::downFile(std::vector<uint8_t> data)
{
    //解析数据包
    std::function<void()> task = [this,data](){
        CloudDrive::FileInfo fileInfo;
        std::memcpy(&fileInfo,data.data(),sizeof (CloudDrive::FileInfo));

        //data size
        std::vector<uint8_t> filedata(data.begin()+sizeof (CloudDrive::FileInfo),data.end());
        std::string fileName = fileInfo.filename;
        std::string fileIdenter = fileInfo.fileIdentfir;
        {
            // 使用获取到的互斥锁保护文件操作
            std::lock_guard<std::mutex> fileLock(fileMutex(fileIdenter));
            std::string fileWritePath = defDownPath+fileName;
            qDebug()<<QString::fromStdString(fileIdenter)<<"\tsize:"<<filedata.size()<<"\tid:"<<fileInfo.dataBlockId;
            // 确保目录存在
            // 确保目录存在（C++11 兼容版本）
            QFileInfo fileInfo1(QString::fromStdString(fileWritePath));
            QDir dir = fileInfo1.absoluteDir();
            if (!dir.exists()) {
                if (!dir.mkpath(".")) {
                    qDebug() << "Failed to create directory:" << dir.absolutePath();
                    return;
                }
            }

            // 使用QFile替代std::fstream
            QFile file(QString::fromStdString(fileWritePath));
            if (!file.open(QIODevice::ReadWrite)) {
                qDebug() << "Failed to open file:" << file.fileName()
                         << "Error:" << file.errorString();
                return;
            }

            // 定位到指定偏移量
            if (!file.seek(fileInfo.offset)) {
                file.close();
                return;
            }

            // 写入数据
            qint64 bytesWritten = file.write(reinterpret_cast<const char*>(filedata.data()), filedata.size());
            if (bytesWritten == -1) {
                qDebug() << "Write error:" << file.errorString();
            } else {
//                qDebug() << "Successfully wrote" << bytesWritten << "bytes";
            }

            file.close();  // 关闭文件（原代码中的fi.close()是多余的，已修正为file.close()）
        }
        int funishPer = double(double(fileInfo.offset+fileInfo.chunk_size)/fileInfo.total_size)*100;
        emit FunishDownFile(fileIdenter,funishPer);
    };
    Client::getInstance().addFunc(task);

}


